package com.henrybit.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.henrybit.annotation.Overload;
import com.henrybit.entity.LandHotelRelation;
import com.henrybit.exception.DBException;
import com.henrybit.util.Constant;
import com.henrybit.util.DBFactory;

/**
 * 岛屿酒店关系查询DAO<p>
 * @author henrybit
 * @version 1.0
 */
public class LandHotelRelationDao extends BaseDao<LandHotelRelation> {

	/**查询基础SQL*/
	private static String queryPre = "select * from land_hotel_relation where 1=1";
	
	@Override
	public List<LandHotelRelation> query(LandHotelRelation t) throws DBException {
		List<LandHotelRelation> list = new ArrayList<LandHotelRelation>();
		String sql = prepareQuerySql(t);
		Connection con = DBFactory.getConnection();
		PreparedStatement ps = null;
		try {
			con.setAutoCommit(false);
			ps = con.prepareStatement(sql);
			ResultSet rs = ps.getResultSet();
			while(rs.next()) {
				LandHotelRelation landHotelRelation = getLandHotelRelation(rs);
				list.add(landHotelRelation);
			}
			rs.close();
			ps.close();
		} catch (Exception e) {
			throw new DBException(e, Constant.DB_QUERY_LAND_HOTEL_RELATION_ERROR, "查询岛屿酒店关系异常");
		} finally {
			try {
				con.close();
			} catch(SQLException e) {
				throw new DBException(e, Constant.DB_CONNECTION_CLOSE_ERROR, "关闭数据库连接异常");
			}
		}
		return list;
	}
	
	@Override
	public void insert(LandHotelRelation t) throws DBException {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean update(LandHotelRelation t) throws DBException {
		// TODO Auto-generated method stub
		return false;
	}
	
	private String prepareQuerySql(LandHotelRelation t) {
		int landId = t.getLandId();
		int hotelId = t.getHotelId();
		StringBuilder sql = new StringBuilder(queryPre);
		if(landId > 0) {
			sql.append(" and landId=").append(landId);
		}
		if(hotelId > 0) {
			sql.append(" and hotelId=").append(hotelId);
		}
		return sql.toString();
	}

	private LandHotelRelation getLandHotelRelation(ResultSet rs) throws DBException {
		LandHotelRelation landHotelRelation = new LandHotelRelation();
		try {
			int landId = rs.getInt("landId");
			int hotelId = rs.getInt("hotelId");
			landHotelRelation.setLandId(landId);
			landHotelRelation.setHotelId(hotelId);
		} catch (Exception e) {
			throw new DBException(e, Constant.DB_LAND_HOTEL_PREPARE_DATA_ERROR, "封装岛屿酒店关系信息异常");
		}
		return landHotelRelation;
	}
}
